local H = require "packages/new_heg/util"
local HC = require "packages/new_hegcomplements/util"
local U = require "packages/utility/utility"
local extension = Package:new("tyheg")
extension.extensionName = "new_hegcomplements"
extension.game_modes_whitelist = { 'ex_heg_mode', 'mul_heg_mode' }

Fk:loadTranslationTable {
  ["tyheg"] = "十周年",
  ["ty_hc_heg"] = "十周年",
}

local jianggan = General(extension, "ty_hc_heg__jianggan", "wei", 3)
local weicheng = fk.CreateTriggerSkill{
  name = "ty_hc__weicheng",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or player:getHandcardNum() >= player.hp then return false end
    for _, move in ipairs(data) do
      if move.from and move.from == player.id and move.to and move.to ~= player.id and move.toArea == Card.PlayerHand then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand then
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
local daoshu = fk.CreateActiveSkill{
  name = "ty_hc__daoshu",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local suits = {"log_spade", "log_club", "log_heart", "log_diamond"}
    local choice = room:askForChoice(player, suits, self.name)
    room:sendLog{
      type = "#ty_hc__DaoshuLog",
      from = player.id,
      to = effect.tos,
      arg = choice,
      arg2 = self.name,
      toast = true,
    }
    local card = room:askForCardChosen(player, target, "h", self.name)
    local count = #(room.logic.event_recorder[GameEvent.MoveCards] or Util.DummyTable)
    room:obtainCard(player, card, true, fk.ReasonPrey, player.id, self.name)
    local e = HC.GetRecentMoveEventByskill(room, self.name, count)
    if not e then return end
    for _, move in ipairs(e.data) do
      for _, info in ipairs(move.moveInfo) do
        card = info.cardId
      end
    end
    if not card or room:getCardOwner(card) ~= player or room:getCardArea(card) ~= Card.PlayerHand then return end
    if Fk:getCardById(card):getSuitString(true) == choice then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
      player:addSkillUseHistory(self.name, -1)
    else
      local suit = Fk:getCardById(card):getSuitString(true)
      table.removeOne(suits, suit)
      suits = table.map(suits, function(s) return s:sub(5) end)
      local others = table.filter(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getSuitString(true) ~= suit end)
      if #others > 0 then
        local cards = room:askForCard(player, 1, 1, false, self.name, false, ".|.|"..table.concat(suits, ","),
          "#ty_hc__daoshu-give::"..target.id..":"..suit)
        if #cards > 0 then
          cards = cards[1]
        else
          cards = table.random(others)
        end
        room:obtainCard(target, cards, true, fk.ReasonGive)
      else
        player:showCards(player:getCardIds(Player.Hand))
      end
    end
  end,
}

jianggan:addSkill(daoshu)
jianggan:addSkill(weicheng)

Fk:loadTranslationTable{
  ["ty_hc_heg__jianggan"] = "蒋干",
  ["#ty_hc_heg__jianggan"] = "锋谪悬信",
  --["designer:ty_hc_heg__jianggan"] = "韩旭",
  ["illustrator:ty_hc_heg__jianggan"] = "biou09",
  ["ty_hc__weicheng"] = "伪诚",
  [":ty_hc__weicheng"] = "你交给其他角色手牌，或你的手牌被其他角色获得后，若你的手牌数小于体力值，你可以摸一张牌。",
  ["ty_hc__daoshu"] = "盗书",
  [":ty_hc__daoshu"] = "出牌阶段限一次，你可以选择一名其他角色并选择一种花色，然后获得其一张手牌。若此牌与你选择的花色："..
  "相同，你对其造成1点伤害且此技能视为未发动过；不同，你交给其一张其他花色的手牌（若没有需展示所有手牌）。",
  ["#ty_hc__DaoshuLog"] = "%from 对 %to 发动了 “%arg2”，选择了 %arg",
  ["#ty_hc__daoshu-give"] = "盗书：交给 %dest 一张非%arg手牌",

  ["$ty_hc__weicheng1"] = "略施谋略，敌军便信以为真。",
  ["$ty_hc__weicheng2"] = "吾只观雅规，而非说客。",
  ["$ty_hc__daoshu1"] = "得此文书，丞相定可高枕无忧。",
  ["$ty_hc__daoshu2"] = "让我看看，这是什么机密。",
  ["~ty_hc_heg__jianggan"] = "丞相，再给我一次机会啊！",
}

local lvlingqi = General(extension, "ty_hc_heg__lvlingqi", "qun", 4, 4, General.Female)
lvlingqi.mainMaxHpAdjustedValue = -1

local guowu = fk.CreateTriggerSkill{
  name = "ty_hc__guowu",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and not player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = player:getCardIds(Player.Hand)
    player:showCards(cards)
    room:delay(300)
    local types = {}
    for _, id in ipairs(cards) do
      table.insertIfNeed(types, Fk:getCardById(id).type)
    end
    local card = room:getCardsFromPileByRule("slash", 1, "discardPile")
    if #card > 0 then
      room:moveCards({
        ids = card,
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        proposer = player.id,
        skillName = self.name,
      })
    end
    if #types > 1 then
      room:addPlayerMark(player, "ty_hc__guowu2-phase", 1)
    end
    if #types > 2 then
      room:addPlayerMark(player, "ty_hc__guowu3-phase", 1)
    end
  end,
}

local guowu_delay = fk.CreateTriggerSkill{
  name = "#ty_hc__guowu_delay",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.CardUsing},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("ty_hc__guowu3-phase") > 0 and not player.dead and
      (data.card.type == Card.TypeBasic or data.card.type == Card.TypeTrick and data.card.sub_type ~= Card.SubtypeDelayedTrick)
      and #player.room:getUseExtraTargets(data) > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = room:getUseExtraTargets(data)
    if #targets == 0 then return false end
    local tos = room:askForChoosePlayers(player, targets, 1, 2, "#ty_hc__guowu-choose:::"..data.card:toLogString(), guowu.name, true)
    if #tos > 0 then
      table.forEach(tos, function (id)
        table.insert(data.tos, {id})
      end)
      room:removePlayerMark(player, "ty_hc__guowu3-phase", 1)
    end
  end,
}

local guowu_targetmod = fk.CreateTargetModSkill{
  name = "#ty_hc__guowu_targetmod",
  bypass_distances =  function(self, player)
    return player:getMark("ty_hc__guowu2-phase") > 0
  end,
}

local wushuangZR = fk.CreateTriggerSkill{
  name = "ty_hc__zhuanrong_hs_wushuang",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified, fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then
      return false
    end
    if event == fk.TargetSpecified then
      return target == player and table.contains({ "slash", "duel" }, data.card.trueName)
    else
      return data.to == player.id and data.card.trueName == "duel"
    end
  end,
  on_use = function(self, event, target, player, data)
    data.fixedResponseTimes = data.fixedResponseTimes or {}
    if data.card.trueName == "slash" then
      data.fixedResponseTimes["jink"] = 2
    else
      data.fixedResponseTimes["slash"] = 2
      data.fixedAddTimesResponsors = data.fixedAddTimesResponsors or {}
      table.insert(data.fixedAddTimesResponsors, (event == fk.TargetSpecified and data.to or data.from))
    end
  end,
}

local zhuangrong = fk.CreateActiveSkill{
  name = "ty_hc__zhuangrong",
  anim_type = "offensive",
  card_num = 1,
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected, player)
    local card = Fk:getCardById(to_select)
    return #selected == 0 and card.type == Card.TypeTrick and not player:prohibitDiscard(to_select)
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, from, from)
    if from.dead then return end
    room:setPlayerMark(from, "@@ty_hc__zhuanrong_hs_wushuang-phase", 1)
    room:handleAddLoseSkills(from, "ty_hc__zhuanrong_hs_wushuang", nil)
    room.logic:getCurrentEvent():findParent(GameEvent.Phase):addCleaner(function()
      room:handleAddLoseSkills(from, "-ty_hc__zhuanrong_hs_wushuang", nil, true, false)
    end)
  end,
}

local shenwei = fk.CreateTriggerSkill{
  name = "ty_hc__shenwei",
  relate_to_place = "m",
  anim_type = "drawcard",
  events = {fk.DrawNCards},
  --frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    data.n = data.n + 2
  end,
}

local shenwei_maxcards = fk.CreateMaxCardsSkill{
  name = "#ty_hc__shenwei_maxcards",
  correct_func = function(self, player)
    if player:hasShownSkill(shenwei) then
      return 2
    end
  end
}

guowu:addRelatedSkill(guowu_delay)
guowu:addRelatedSkill(guowu_targetmod)
lvlingqi:addSkill(guowu)
lvlingqi:addSkill(zhuangrong)
shenwei:addRelatedSkill(shenwei_maxcards)
lvlingqi:addSkill(shenwei)
lvlingqi:addRelatedSkill(wushuangZR)

Fk:loadTranslationTable{
  ["ty_hc_heg__lvlingqi"] = "吕玲绮",
  ["#ty_hc_heg__lvlingqi"] = "无双虓姬",
  --["designer:ty_hc_heg__lvlingqi"] = "xat1k",
  ["illustrator:ty_hc_heg__lvlingqi"] = "君桓文化",

  ["ty_hc__guowu"] = "帼武",
  ["#ty_hc__guowu_delay"] = "帼武",
  [":ty_hc__guowu"] = "出牌阶段开始时，你可展示所有手牌，若包含的类别数：不小于1，你从弃牌堆中获得一张【杀】；不小于2，你本阶段使用牌无距离限制；"..
  "不小于3，你本阶段使用【杀】或普通锦囊牌可以多指定两个目标（限一次）。",
  ["ty_hc__zhuangrong"] = "妆戎",
  [":ty_hc__zhuangrong"] = "出牌阶段限一次，你可以弃置一张锦囊牌，然后获得“无双”至此阶段结束。",
  ["ty_hc__shenwei"] = "神威",
  [":ty_hc__shenwei"] = "主将技，此武将牌上单独的阴阳鱼个数-1；摸牌阶段，你多摸两张牌；你的手牌上限+2。",
  ["ty_hc__zhuanrong_hs_wushuang"] = "无双",
  ["@@ty_hc__zhuanrong_hs_wushuang-phase"] = "无双",
  [":ty_hc__zhuanrong_hs_wushuang"] = "锁定技，当你使用【杀】指定一个目标后，该角色需依次使用两张【闪】才能抵消此【杀】；当你使用【决斗】指定一个目标后，或成为一名角色使用【决斗】的目标后，该角色每次响应此【决斗】需依次打出两张【杀】。",
  ["#ty_hc__guowu-choose"] = "帼武：你可以为 %arg 增加至多两个目标",

  ["$ty_hc__guowu1"] = "方天映黛眉，赤兔牵红妆。",
  ["$ty_hc__guowu2"] = "武姬青丝利，巾帼女儿红。",
  ["$ty_hc__shenwei1"] = "锋镝鸣手中，锐戟映秋霜。",
  ["$ty_hc__shenwei2"] = "红妆非我愿，学武觅封侯。",
  ["$ty_hc__zhuangrong1"] = "继父神威，无坚不摧！",
  ["$ty_hc__zhuangrong2"] = "我乃温侯吕奉先之女！",
  ["$ty_hc__zhuanrong_hs_wushuang1"] = "猛将策良骥，长戟破敌营。",
  ["$ty_hc__zhuanrong_hs_wushuang2"] = "杀气腾剑戟，严风卷戎装。",
  ["~ty_hc_heg__lvlingqi"] = "父亲，女儿好累……",
}

local nanhualaoxian = General(extension, "ty_hc_heg__nanhualaoxian", "qun", 4)

local jinghe = fk.CreateActiveSkill{
  name = "ty_hc__jinghe",
  anim_type = "support",
  min_card_num = 1,
  min_target_num = 1,
  prompt = "#ty_hc__jinghe",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    if #selected < Self.maxHp and Fk:currentRoom():getCardArea(to_select) == Player.Hand then
      if #selected == 0 then
        return true
      else
        return table.every(selected, function(id) return Fk:getCardById(to_select).trueName ~= Fk:getCardById(id).trueName end)
      end
    end
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected < #selected_cards and H.getGeneralsRevealedNum(Fk:currentRoom():getPlayerById(to_select)) > 0
  end,
  feasible = function (self, selected, selected_cards)
    return #selected > 0 and #selected == #selected_cards
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:showCards(effect.cards)
    room:sortPlayersByAction(effect.tos)
    local num = 0 + #effect.tos
    local skills = table.random({"le_hc__leiji", "le_hc__yinbingn", "le_hc__huoqi", "le_hc__guizhu", "le_hc__xianshou", "le_hc__lundao", "le_hc__guanyue", "le_hc__yanzhengn"}, num)
    for _, id in ipairs(effect.tos) do
      local p = room:getPlayerById(id)
      if not p.dead then
        local choices = table.filter(skills, function(s) return not p:hasSkill(s, true) end)
        if #choices > 0 then
          local choice
          local result = room:askForCustomDialog(p, self.name,
            "packages/utility/qml/ChooseSkillBox.qml", {
              choices, 0, 1, "#ty_hc__jinghe-choice"
            })
          if result ~= "" then
            local schoice = json.decode(result)
            if #schoice > 0 then
              choice = schoice[1]
            end
          end
          if choice then
            table.removeOne(skills, choice)
            room:addTableMark(player, self.name, {p.id, choice})
            room:addTableMark(p, "@ty_hc__jinghe", choice)
            room:handleAddLoseSkills(p, choice, nil, true, false)
          end
        end
      end
    end
  end,
}
local jinghe_trigger = fk.CreateTriggerSkill {
  name = "#ty_hc__jinghe_trigger",
  mute = true,
  events = {fk.TurnStart, fk.Death},
  can_trigger = function(self, event, target, player, data)
    return target == player and #player:getTableMark("ty_hc__jinghe") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, table in ipairs(player:getTableMark("ty_hc__jinghe")) do
      local p = room:getPlayerById(table[1])
      room:removeTableMark(p, "@ty_hc__jinghe", table[2])
      room:handleAddLoseSkills(p, "-"..table[2], nil, true, false)
    end
    room:setPlayerMark(player, "ty_hc__jinghe", 0)
  end,
}

jinghe:addRelatedSkill(jinghe_trigger)
nanhualaoxian:addSkill("le_hc__gongxiu")
nanhualaoxian:addSkill(jinghe)
nanhualaoxian:addRelatedSkill("le_hc__leiji")
nanhualaoxian:addRelatedSkill("le_hc__yinbingn")
nanhualaoxian:addRelatedSkill("le_hc__huoqi")
nanhualaoxian:addRelatedSkill("le_hc__guizhu")
nanhualaoxian:addRelatedSkill("le_hc__xianshou")
nanhualaoxian:addRelatedSkill("le_hc__lundao")
nanhualaoxian:addRelatedSkill('le_hc__guanyue')
nanhualaoxian:addRelatedSkill('le_hc__yanzhengn')

Fk:loadTranslationTable{
  ["ty_hc_heg__nanhualaoxian"] = "南华老仙",
  ["#ty_hc_heg__nanhualaoxian"] = "仙人指路",
  ["illustrator:ty_hc_heg__nanhualaoxian"] = "君桓文化",

  ["ty_hc__jinghe"] = "经合",
  [":ty_hc__jinghe"] = "每回合限一次，出牌阶段，你可展示至多X张牌名各不同的手牌并选择等量有明置武将牌的角色，从“写满技能的天书”随机展示X个技能，这些角色依次可以选择并"..
  "获得其中一个技能，直到你下回合开始 （X为你的体力上限）。",

  ["#ty_hc__jinghe"] = "经合：展示至多体力上限张牌名各不同的手牌，令等量的角色获得技能",
  ["#ty_hc__jinghe-choice"] = "经合：你可选择获得一个技能",
  ["@ty_hc__jinghe"] = "经合",

  ["$ty_hc__jinghe1"] = "大哉乾元，万物资始。",
  ["$ty_hc__jinghe2"] = "无极之外，复无无极。",
  ["~ty_hc_heg__nanhualaoxian"] = "道亦有穷时……",
}

return extension